package com.moss.cloud.auth.biz.controller;

import com.moss.cloud.auth.biz.model.from.CaptchaFrom;
import com.moss.cloud.common.core.constant.ServiceList;
import com.moss.cloud.common.core.model.Result;
import com.ramostear.captcha.HappyCaptcha;
import com.ramostear.captcha.common.Fonts;
import com.ramostear.captcha.support.CaptchaStyle;
import com.ramostear.captcha.support.CaptchaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 微服务验证码控制器
 *
 * @Author: 瑾年
 * @Date: 2020-5-23
 */
@RestController
@RequestMapping(ServiceList.AUTH + "/captcha")
public class CaptchaController {
    /**
     * 获取验证码
     *
     * @param res
     * @param req
     * @Author: 瑾年
     * @Date: 2020-5-23
     */
    @GetMapping("/captchaCode")
    public void captcha(HttpServletRequest req, HttpServletResponse res) {
        HappyCaptcha.require(req, res)
                .style(CaptchaStyle.IMG)            //设置展现样式为动画
                .type(CaptchaType.DEFAULT)            //数字加英文字母
                .length(4)                            //设置字符长度为6
                .width(220)                            //设置动画宽度为220
                .height(80)                            //设置动画高度为80
                .font(Fonts.getInstance().zhFont())    //设置汉字的字体
                .build().finish();                //生成并输出验证码
    }

    /**
     * 校验验证码
     *
     * @param captchaFrom
     * @param request
     * @Author: 瑾年
     * @Date: 2020-5-23
     */
    @PostMapping("/verify")
    public Result verify(HttpServletRequest request, @RequestBody CaptchaFrom captchaFrom) {
        boolean flag = HappyCaptcha.verification(request, captchaFrom.getCode(), true);
        if (Boolean.TRUE.equals(flag)) {
            HappyCaptcha.remove(request);
            return Result.success();
        }
        return Result.fail();
    }

    /**
     * 移除验证码
     *
     * @param request
     * @Author: 瑾年
     * @Date: 2020-5-23
     */
    @GetMapping("/remove")
    public void removeCaptcha(HttpServletRequest request) {
        HappyCaptcha.remove(request);
    }
}
